<template>
  <div class="admin-container">
    <!-- 登录界面 -->
    <div v-if="!isAuthenticated" class="login-container">
      <div class="login-card">
        <h2 class="login-title">管理员登录</h2>
        <div class="login-form">
          <div class="form-group">
            <label>账号</label>
            <input
              v-model="state.loginForm.username"
              placeholder="管理员账号"
              type="text"
            />
          </div>
          <div class="form-group">
            <label>密码</label>
            <input
              v-model="state.loginForm.password"
              type="password"
              placeholder="密码"
            />
          </div>
          <button @click="handleLogin" class="login-btn">登录</button>
        </div>
      </div>
    </div>

    <!-- 后台主界面 -->
    <div v-else class="admin-main">
      <div class="header">
        <div class="welcome">欢迎，管理员</div>
        <button @click="logout" class="logout-btn">退出登录</button>
      </div>

      <!-- 上传区域 -->
      <div class="card">
        <h3 class="card-title">歌曲上传</h3>
        <div class="upload-area" @click="triggerFileInput">
          <div v-if="!state.selectedFile">
            <i class="el-icon-upload upload-icon"></i>
            <div class="upload-text">点击上传音乐文件</div>
            <div class="upload-hint">支持MP3格式，最大50MB</div>
          </div>
          <div v-else class="file-info">
            {{ state.selectedFile.name }} ({{
              formatSize(state.selectedFile.size)
            }})
          </div>
          <input
            type="file"
            ref="fileInput"
            @change="handleFileChange"
            hidden
            accept="audio/mpeg"
          />
        </div>
        <div class="form-row">
          <div class="form-group">
            <input
              v-model="state.uploadForm.title"
              placeholder="歌曲名称"
              required
            />
          </div>
          <div class="form-group">
            <input
              v-model="state.uploadForm.artist"
              placeholder="歌手名称"
              required
            />
          </div>
        </div>

        <button
          @click="uploadSong"
          :disabled="
            !state.selectedFile ||
            !state.uploadForm.title ||
            !state.uploadForm.artist
          "
          class="submit-btn"
        >
          确认上传
        </button>
      </div>

      <!-- 数据管理 -->
      <div class="data-tabs">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="歌曲管理" name="songs">
            <el-table :data="state.songs">
              <el-table-column prop="songtitle" label="歌曲名称" width="650" />
              <el-table-column prop="songauthor" label="歌手" width="650" />
              <el-table-column label="操作" width="100">
                <template #default="{ row }">
                  <el-button
                    type="danger"
                    size="small"
                    @click="deleteItem('song', row.id)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <el-tab-pane label="用户管理" name="users">
            <el-table :data="state.users">
              <el-table-column prop="username" label="用户名" width="500" />
              <el-table-column prop="email" label="邮箱" width="500" />
              <el-table-column prop="phone" label="手机号" width="300" />
              <el-table-column label="操作" width="100">
                <template #default="{ row }">
                  <el-button
                    type="danger"
                    size="small"
                    @click="deleteItem('user', row.id)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";

const router = useRouter();
const fileInput = ref(null);
const activeTab = ref("songs");
const isAuthenticated = ref(!!localStorage.getItem("userToken"));

const state = reactive({
  loginForm: { username: "", password: "" },
  uploadForm: { title: "", artist: "" },
  songs: [],
  users: [],
  selectedFile: null,
  loading: false,
});

// 数据加载函数
const fetchData = async () => {
  state.loading = true;
  try {
    const token = localStorage.getItem("userToken");
    if (!token) throw new Error("未登录");

    const [songsRes, usersRes] = await Promise.all([
      axios.get("http://localhost:3001/api/songs", {
        headers: { Authorization: `Bearer ${token}` },
      }),
      axios.get("http://localhost:3001/api/users", {
        headers: { Authorization: `Bearer ${token}` },
      }),
    ]);

    state.songs = songsRes.data;
    state.users = usersRes.data;
  } catch (error) {
    console.error("数据加载失败:", error);
    ElMessage.error("数据加载失败，请重试");
    if (error.response?.status === 401) {
      logout(); // token过期时自动退出登录
    }
  } finally {
    state.loading = false;
  }
};

// 管理员登录
const handleLogin = async () => {
  try {
    const res = await axios.post(
      "http://localhost:3001/api/login",
      state.loginForm
    );
    const user = res.data.user;

    if (user && user.is_admin === 1) {
      localStorage.setItem("userToken", user.token);
      isAuthenticated.value = true;
      ElMessage.success("登录成功");
      await fetchData();
    } else {
      ElMessage.error("非管理员账户或认证失败");
    }
  } catch (error) {
    console.error("登录错误:", error);
    ElMessage.error("登录失败，请检查账号密码");
  }
};

// 退出登录
const logout = () => {
  localStorage.removeItem("userToken");
  isAuthenticated.value = false;
  router.push("/login"); // 跳转到登录页（需配置路由）
  ElMessage.success("退出登录成功");
};

// 组件挂载时加载数据
onMounted(() => {
  if (isAuthenticated.value) fetchData();
});

// 文件上传相关函数
const triggerFileInput = () => {
  fileInput.value.click();
};

const handleFileChange = (e) => {
  const file = e.target.files[0];
  if (file && file.type === "audio/mpeg" && file.size <= 50 * 1024 * 1024) {
    state.selectedFile = file;
  } else {
    ElMessage.error("请选择正确格式的文件（MP3，最大50MB）");
    e.target.value = null; // 清除无效文件
  }
};

const uploadSong = async () => {
  if (!state.selectedFile) return ElMessage.warning("请选择上传文件");

  const formData = new FormData();
  formData.append("file", state.selectedFile);
  formData.append("title", state.uploadForm.title);
  formData.append("artist", state.uploadForm.artist);

  try {
    await axios.post("http://localhost:3001/api/songs", formData, {
      headers: {
        Authorization: `Bearer ${localStorage.getItem("userToken")}`,
      },
    });

    ElMessage.success("歌曲上传成功");
    state.selectedFile = null;
    state.uploadForm = { title: "", artist: "" };
    await fetchData(); // 刷新数据
  } catch (error) {
    console.error("上传失败:", error);
    if (error.response) {
      ElMessage.error(
        `上传失败 (${error.response.status}): ${error.response.data.error}`
      );
    } else if (error.message) {
      ElMessage.error(`上传失败: ${error.message}`);
    } else {
      ElMessage.error("歌曲上传失败，请重试");
    }
  }
};

// 删除操作
const deleteItem = async (type, id) => {
  try {
    if (type === "song") {
      await ElMessageBox.confirm("确定要删除这首歌曲吗？", "警告", {
        type: "warning",
      });

      await axios.delete(`http://localhost:3001/api/songs/${id}`, {
        headers: {
          Authorization: `Bearer ${localStorage.getItem("userToken")}`,
        },
      });

      ElMessage.success("歌曲删除成功");
      await fetchData();
    } else if (type === "user") {
      const user = state.users.find((u) => u.id === id);
      if (user.id === 1) {
        return ElMessage.error("禁止删除超级管理员");
      }

      await ElMessageBox.confirm("确定要删除该用户吗？", "警告", {
        type: "warning",
      });

      await axios.delete(`http://localhost:3001/api/users/${id}`, {
        headers: {
          Authorization: `Bearer ${localStorage.getItem("userToken")}`,
        },
      });

      ElMessage.success("用户删除成功");
      await fetchData();
    }
  } catch (error) {
    if (error.response?.status === 403) {
      ElMessage.error("权限不足，禁止删除超级管理员");
    } else {
      console.error("删除失败:", error);
      ElMessage.error("删除操作失败，请重试");
    }
  }
};

// 格式化文件大小
const formatSize = (size) => {
  if (size >= 1024 * 1024) return `${(size / (1024 * 1024)).toFixed(2)} MB`;
  if (size >= 1024) return `${(size / 1024).toFixed(2)} KB`;
  return `${size} B`;
};
</script>

<style scoped>
/* 深度样式重置 */
:deep(*) {
  box-sizing: border-box;
  font-family: "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
}

/* 统一容器 */
.admin-container {
  min-height: 100vh;
  background: linear-gradient(45deg, #0a0a0a 0%, #1a1a1a 100%);
}

/* 登录页完全匹配注册页 */
.login-container {
  background: linear-gradient(45deg, #0a0a1f 0%, #1a1a3e 100%);
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

.login-card {
  width: 500px;
  padding: 50px;
  background: rgba(17, 17, 17, 0.95);
  border-radius: 20px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.7);
  border: 1px solid rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(12px);
}

/* 主界面完全统一 */
.admin-main {
  padding: 40px 5%;
  min-height: 100vh;
}

/* 头部增强 */
.header {
  background: rgba(17, 17, 17, 0.95);
  backdrop-filter: blur(12px);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 15px;
  padding: 20px 40px;
  margin-bottom: 40px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
}

.welcome {
  font-size: 24px;
  background: linear-gradient(45deg, #ff4d4f 0%, #ff1919 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  letter-spacing: 0.5px;
}

/* 卡片全面统一 */
.card {
  background: rgba(17, 17, 17, 0.9);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 15px;
  padding: 30px;
  margin-bottom: 40px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(12px);
  transition: transform 0.3s ease;
}

.card:hover {
  transform: translateY(-5px);
}

.card-title {
  font-size: 20px;
  color: #ff4d4f;
  padding-bottom: 15px;
  margin-bottom: 25px;
  border-bottom: 3px solid;
  border-image: linear-gradient(90deg, #ff4d4f 0%, #ff1919 100%) 1;
}

/* 上传区域完全匹配 */
.upload-area {
  border: 2px dashed rgba(255, 77, 79, 0.3);
  background: rgba(30, 30, 30, 0.4);
  border-radius: 15px;
  padding: 40px;
  transition: all 0.3s ease;
  cursor: pointer;
}

.upload-area:hover {
  border-color: #ff4d4f;
  background: rgba(255, 77, 79, 0.1);
  box-shadow: 0 0 20px rgba(255, 77, 143, 0.2);
}

.upload-icon {
  font-size: 48px;
  color: #ff4d4f;
  margin-bottom: 15px;
}

.upload-text {
  color: rgba(255, 255, 255, 0.9);
  font-size: 18px;
  margin-bottom: 8px;
}

.upload-hint {
  color: rgba(255, 255, 255, 0.6);
  font-size: 14px;
}

/* 表单元素完全统一 */
.form-row {
  display: flex;
  gap: 25px;
  margin-bottom: 25px;
}

.form-group {
  flex: 1;
}

.form-group input {
  width: 100%;
  padding: 14px 24px;
  background: rgba(30, 30, 30, 0.9);
  border: 1px solid rgba(255, 255, 255, 0.15);
  border-radius: 30px;
  color: rgba(255, 255, 255, 0.9);
  font-size: 16px;
  transition: all 0.3s ease;
}

.form-group input:focus {
  border-color: #ff4d4f;
  box-shadow: 0 0 15px rgba(255, 77, 79, 0.3);
}

.form-group input::placeholder {
  color: rgba(255, 255, 255, 0.4);
}

/* 按钮完全统一 */
.submit-btn,
.logout-btn {
  background: linear-gradient(45deg, #ff4d4f 0%, #ff1919 100%);
  border: none;
  border-radius: 30px;
  color: white;
  padding: 14px 28px;
  font-size: 16px;
  font-weight: 600;
  letter-spacing: 0.5px;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.submit-btn:hover,
.logout-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 20px rgba(255, 77, 79, 0.5);
}

.submit-btn:disabled {
  background: linear-gradient(45deg, #444 0%, #666 100%);
  cursor: not-allowed;
  opacity: 0.7;
}

/* 表格深度定制 */
:deep(.el-table) {
   width: 100% !important;
  --el-table-border-color: rgb(18, 18, 18)
  --el-table-header-bg-color: rgb(18, 18, 18); /* 修改 */
  --el-table-tr-bg-color: rgb(18, 18, 18)
  --el-table-row-hover-bg-color: rgb(18, 18, 18)
}

:deep(.el-table th) {
  background:rgb(18, 18, 18) !important; /* 修改 */
  color: #ff4d4f !important;
  font-weight: 600;
  font-size: 16px;
}

:deep(.el-table td) {
  background: rgb(18, 18, 18); /* 新增 */
  font-size: 15px;

}

:deep(.el-table tr) {
  width: inherit !important;  /* 继承表格宽度 */
  display: table-row;  /* 保持默认表格布局 */
  background: #424242;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); /* 添加平滑过渡 */
}

:deep(.el-table tr:hover) {
  background: linear-gradient(
    45deg,

    #ff4d4f 100%
  ) !important;
  box-shadow: inset 0 0 15px rgba(255, 77, 79, 0.3); /* 添加内阴影增强效果 */
}

:deep(.el-table__body tr:hover > td) {
  background-color: #535353 !important; /* 修改 */
   background: transparent !important; /* 使td背景透明以显示行背景 */
}

:deep(.el-table__inner-wrapper::before) {
  background-color: rgba(255, 255, 255, 0.1);
}

/* 分页组件 */
:deep(.el-pagination) {
  --el-pagination-bg-color: transparent;
  --el-pagination-button-disabled-bg-color: transparent;
  --el-pagination-hover-color: #ff4d4f;
  padding: 20px 0;
}

:deep(.el-pager li) {
  background: rgba(30, 30, 30, 0.9);
  color: rgba(255, 255, 255, 0.7);
  min-width: 36px;
  border-radius: 8px;
  margin: 0 4px;
}

:deep(.el-pager li.is-active) {
  background: #ff4d4f;
  color: white;
}

/* 响应式全面适配 */
@media (max-width: 768px) {
  .login-card {
    width: 90%;
    padding: 30px;
  }

  .header {
    flex-direction: column;
    gap: 15px;
    padding: 15px;
  }

  .card {
    padding: 20px;
  }

  .form-row {
    flex-direction: column;
    gap: 15px;
  }

  :deep(.el-table) {
    width: 600px;
  }

  :deep(.el-table__body-wrapper) {
    overflow-x: auto;
  }

  .upload-area {
    padding: 30px;
  }
}

/* 加载状态 */
:deep(.el-loading-mask) {
  background-color: rgba(17, 17, 17, 0.9) !important;
}

:deep(.el-loading-spinner .path) {
  stroke: #ff4d4f;
}
</style>
